<template>
  <div class="repository-detail">
    <div class="detail-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/repositories' }">仓库管理</el-breadcrumb-item>
        <el-breadcrumb-item>{{ repository?.name || 'Loading...' }}</el-breadcrumb-item>
      </el-breadcrumb>
      
      <div class="header-actions">
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
        <el-button type="primary" @click="showPushDialog = true">
          <el-icon><Upload /></el-icon>
          推送镜像
        </el-button>
      </div>
    </div>

    <div class="detail-content" v-loading="loading">
      <el-card class="repo-info">
        <template #header>
          <div class="card-header">
            <span>仓库信息</span>
          </div>
        </template>
        
        <el-descriptions :column="2" border>
          <el-descriptions-item label="仓库名称">{{ repository?.name }}</el-descriptions-item>
          <el-descriptions-item label="仓库类型">{{ repository?.type }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(repository?.created_at) }}</el-descriptions-item>
          <el-descriptions-item label="最后更新">{{ formatDate(repository?.updated_at) }}</el-descriptions-item>
          <el-descriptions-item label="镜像数量">{{ repository?.image_count || 0 }}</el-descriptions-item>
          <el-descriptions-item label="总大小">{{ formatSize(repository?.total_size) }}</el-descriptions-item>
          <el-descriptions-item label="描述" :span="2">{{ repository?.description || '暂无描述' }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <el-card class="tags-list">
        <template #header>
          <div class="card-header">
            <span>镜像标签</span>
            <el-input
              v-model="searchTag"
              placeholder="搜索标签"
              style="width: 200px"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
        </template>

        <el-table :data="filteredTags" stripe>
          <el-table-column prop="name" label="标签名称" min-width="150" />
          <el-table-column prop="digest" label="摘要" min-width="200">
            <template #default="{ row }">
              <el-text class="digest-text">{{ row.digest }}</el-text>
            </template>
          </el-table-column>
          <el-table-column prop="size" label="大小" width="120">
            <template #default="{ row }">
              {{ formatSize(row.size) }}
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.created_at) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
              <el-button size="small" @click="copyPullCommand(row)">
                <el-icon><DocumentCopy /></el-icon>
                复制
              </el-button>
              <el-button size="small" type="danger" @click="deleteTag(row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 推送镜像对话框 -->
    <el-dialog v-model="showPushDialog" title="推送镜像" width="600px">
      <div class="push-commands">
        <h4>推送命令：</h4>
        <el-input
          v-model="pushCommand"
          readonly
          type="textarea"
          :rows="3"
        >
          <template #append>
            <el-button @click="copyToClipboard(pushCommand)">
              <el-icon><DocumentCopy /></el-icon>
              复制
            </el-button>
          </template>
        </el-input>
      </div>
      
      <template #footer>
        <el-button @click="showPushDialog = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Refresh,
  Upload,
  Search,
  DocumentCopy,
  Delete
} from '@element-plus/icons-vue'

const route = useRoute()
const repositoryName = route.params.name as string

const loading = ref(false)
const repository = ref<any>(null)
const tags = ref<any[]>([])
const searchTag = ref('')
const showPushDialog = ref(false)

const filteredTags = computed(() => {
  if (!searchTag.value) return tags.value
  return tags.value.filter(tag => 
    tag.name.toLowerCase().includes(searchTag.value.toLowerCase())
  )
})

const pushCommand = computed(() => {
  return `# 登录到仓库
docker login localhost:5000

# 标记镜像
docker tag your-image:tag localhost:5000/${repositoryName}:tag

# 推送镜像
docker push localhost:5000/${repositoryName}:tag`
})

const formatDate = (dateString: string) => {
  if (!dateString) return '-'
  return new Date(dateString).toLocaleString('zh-CN')
}

const formatSize = (bytes: number) => {
  if (!bytes) return '0 B'
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(1024))
  return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i]
}

const fetchRepositoryDetail = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    repository.value = {
      name: repositoryName,
      type: 'Docker',
      created_at: '2024-01-15T10:30:00Z',
      updated_at: '2024-01-20T15:45:00Z',
      image_count: 5,
      total_size: 1024 * 1024 * 512, // 512MB
      description: '这是一个示例容器镜像仓库'
    }
    
    tags.value = [
      {
        name: 'latest',
        digest: 'sha256:abc123def456...',
        size: 1024 * 1024 * 100, // 100MB
        created_at: '2024-01-20T15:45:00Z'
      },
      {
        name: 'v1.0.0',
        digest: 'sha256:def456ghi789...',
        size: 1024 * 1024 * 95, // 95MB
        created_at: '2024-01-18T12:30:00Z'
      },
      {
        name: 'v0.9.0',
        digest: 'sha256:ghi789jkl012...',
        size: 1024 * 1024 * 90, // 90MB
        created_at: '2024-01-15T10:30:00Z'
      }
    ]
  } catch (error) {
    ElMessage.error('获取仓库详情失败')
  } finally {
    loading.value = false
  }
}

const refreshData = () => {
  fetchRepositoryDetail()
}

const copyPullCommand = (tag: any) => {
  const command = `docker pull localhost:5000/${repositoryName}:${tag.name}`
  copyToClipboard(command)
}

const copyToClipboard = async (text: string) => {
  try {
    await navigator.clipboard.writeText(text)
    ElMessage.success('已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

const deleteTag = async (tag: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除标签 "${tag.name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟删除API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    const index = tags.value.findIndex(t => t.name === tag.name)
    if (index > -1) {
      tags.value.splice(index, 1)
    }
    
    ElMessage.success('删除成功')
  } catch (error) {
    // 用户取消删除
  }
}

onMounted(() => {
  fetchRepositoryDetail()
})
</script>

<style scoped>
.repository-detail {
  padding: 20px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.digest-text {
  font-family: monospace;
  font-size: 12px;
}

.push-commands {
  margin-bottom: 20px;
}

.push-commands h4 {
  margin-bottom: 10px;
  color: var(--el-text-color-primary);
}

@media (max-width: 768px) {
  .detail-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>